// 背景网格层
import 'package:flutter/material.dart';
import 'package:flutter_app/constant/const_string.dart';
import 'package:flutter_app/pages/white_board/white_board_vm.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';

class BackgroundLayerWidget extends StatelessWidget {
  const BackgroundLayerWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<WhiteBoardVM>(
      id: ConstString.gridBackgroundWidgetId,
      builder: (WhiteBoardVM whiteBoardVM) {
        return Transform(
            alignment: Alignment.center,
            transform: Matrix4.identity()
              ..translate(whiteBoardVM.curCanvasOffset.dx,
                  whiteBoardVM.curCanvasOffset.dy)
              ..scale(whiteBoardVM.curCanvasScale),
            child: RepaintBoundary(
              child: CustomPaint(
                // size: MediaQuery.of(context).size,
                isComplex: true,
                painter: GridPainter(context: context),
              ),
            ));
      },
    );
  }
}

class GridPainter extends CustomPainter {
  final BuildContext context;
  GridPainter({required this.context});

  @override
  void paint(Canvas canvas, Size size) {
    print(size.width);
    final paint = Paint()
      ..color = const Color.fromARGB(255, 228, 26, 211)
      ..strokeWidth = 1;

    double mediaWidth = MediaQuery.of(context).size.width;
    double mediaHeight = MediaQuery.of(context).size.height;
    const double barWidth = 0;
    final double boardWidth = mediaWidth - 20;
    final xScale = 300 / boardWidth;

    // 绘制主背景色
    // final mainBoardPaint = Paint()..color = Colors.grey.withOpacity(.3);
    // canvas.drawRect(
    //   Rect.fromLTWH(barWidth, barWidth, boardWidth, mediaHeight - barWidth),
    //   mainBoardPaint,
    // );

    // 绘制网格背景色
    final boardPaint = Paint()..color = Colors.white;
    canvas.drawRect(
      Rect.fromLTWH(barWidth, barWidth, boardWidth, boardWidth),
      boardPaint,
    );

    // 绘制网格
    final gridPaint = Paint()
      ..color = Colors.grey.withOpacity(.4)
      ..strokeWidth = 1;
    for (int i = 0; i <= 300; i += 10) {
      final xPosition = (i / xScale) + barWidth;
      canvas.drawLine(Offset(xPosition, barWidth),
          Offset(xPosition, (boardWidth + barWidth)), gridPaint);
    }
    for (int i = 0; i <= 300; i += 10) {
      final yPosition = i / xScale + barWidth;
      canvas.drawLine(Offset(barWidth, yPosition),
          Offset(boardWidth + barWidth, yPosition), gridPaint);
    }

    // for (double i = 0; i <= 300; i += 20) {
    //   canvas.drawLine(Offset(i, 0), Offset(i, 300), paint);
    // }
    // for (double i = 0; i <= 300; i += 20) {
    //   canvas.drawLine(Offset(0, i), Offset(300, i), paint);
    // }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
